package erwiki.ui.app.parts.attachments;

import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import org.eclipse.e4.core.di.annotations.Optional;
import org.eclipse.e4.ui.di.UIEventTopic;
import org.eclipse.e4.ui.services.IServiceConstants;
import org.eclipse.e4.ui.workbench.modeling.ESelectionService;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.elwiki_data.AttachmentContent;
import org.elwiki_data.WikiPage;

import jakarta.annotation.PostConstruct;
import jakarta.inject.Inject;
import jakarta.inject.Named;

public class WikiAttachmentsView {

	@Inject
	ESelectionService selectionService;

	private WikiPage currentWikiPage;

	private TableViewer tableViewer;
	private Table table;

	/**
	 * Create contents of the part.
	 *
	 * @param parent
	 * @wbp.parser.entryPoint
	 */
	@PostConstruct
	public void createPartControl(Composite parent) {
		Composite container = new Composite(parent, SWT.NONE);
		container.setLayout(new GridLayout(1, false));

		tableViewer = new TableViewer(container, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI);
		table = tableViewer.getTable();
		table.setHeaderVisible(true);
		table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

		TableViewerColumn tableViewerColumn_name = new TableViewerColumn(tableViewer, SWT.NONE);
		TableColumn tblclmnName = tableViewerColumn_name.getColumn();
		tblclmnName.setWidth(250);
		tblclmnName.setText("Name");

		TableViewerColumn tableViewerColumn_version = new TableViewerColumn(tableViewer, SWT.NONE);
		TableColumn tblclmnVersion = tableViewerColumn_version.getColumn();
		tblclmnVersion.setWidth(70);
		tblclmnVersion.setText("Version");

		TableViewerColumn tableViewerColumn_date = new TableViewerColumn(tableViewer, SWT.NONE);
		TableColumn tblclmnDate = tableViewerColumn_date.getColumn();
		tblclmnDate.setWidth(180);
		tblclmnDate.setText("Date Creation");

		TableViewerColumn tableViewerColumn_size = new TableViewerColumn(tableViewer, SWT.NONE);
		TableColumn tblclmnSize = tableViewerColumn_size.getColumn();
		tblclmnSize.setWidth(100);
		tblclmnSize.setText("Size");

		TableViewerColumn tableViewerColumn_kind = new TableViewerColumn(tableViewer, SWT.NONE);
		TableColumn tblclmnKind = tableViewerColumn_kind.getColumn();
		tblclmnKind.setWidth(110);
		tblclmnKind.setText("Kind");

		TableViewerColumn tableViewerColumn_author = new TableViewerColumn(tableViewer, SWT.NONE);
		TableColumn tblclmnAuthor = tableViewerColumn_author.getColumn();
		tblclmnAuthor.setWidth(160);
		tblclmnAuthor.setText("Author");

		TableViewerColumn tableViewerColumn_changeNote = new TableViewerColumn(tableViewer, SWT.NONE);
		TableColumn tblclmnChangeNote = tableViewerColumn_changeNote.getColumn();
		tblclmnChangeNote.setWidth(260);
		tblclmnChangeNote.setText("Change note");

		tableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
			@Override
			public void selectionChanged(SelectionChangedEvent event) {
				selectionService.setSelection(event.getStructuredSelection());
			}
		});

		tableViewer.setContentProvider(new ArrayContentProvider());
		tableViewer.setLabelProvider(new AttachmentsLabelProvider());
		setInput(currentWikiPage);
	}

	@Inject
	@Optional
	private void subscribeTopicTodoUpdated(@UIEventTopic(EventsAttachmentsView.TOPIC_ATTACHMENTS_UPDATE) Object obj) {
		if (this.tableViewer != null) {
			setInput(this.currentWikiPage);
		}
	}

	/**
	 * @return Выбранные AttachmentContent.
	 */
	@SuppressWarnings("unchecked")
	public Collection<AttachmentContent> getSelectedAttachments() {
		if (tableViewer.getSelection() instanceof IStructuredSelection ss
				&& ss.getFirstElement() instanceof AttachmentContent) {
			return ss.toList();
		}
		return Collections.emptyList();
	}

	@Inject
	public void reactOnSelection(@Optional @Named(IServiceConstants.ACTIVE_SELECTION) WikiPage wikiPage) {
		if (wikiPage != null) {
			currentWikiPage = wikiPage;
			setInput(wikiPage);
		}
	}

	private void setInput(WikiPage wikiPage) {
		if (wikiPage == null || tableViewer == null) {
			return;
		}

		// Получить список всех AttachmentContent.
		List<AttachmentContent> listAttContent = wikiPage.getAttachments().stream()
				.flatMap(attachment -> attachment.getAttachContents().stream()).collect(Collectors.toList());

		// Сортировать: Name - по возрастанию, Version - по убыванию. Поэтому, 2 раза reversed().
		Comparator<AttachmentContent> histInfoComparator = Comparator.comparing(AttachmentContent::getName).reversed()
				.thenComparingInt(AttachmentContent::getVersion).reversed();
		Collections.sort(listAttContent, histInfoComparator);

		tableViewer.setInput(listAttContent);
	}

}
